var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op
var db = require('../models')

/* GET users listing. */
router.get('/', async function (req, res, next) {
  try {
    if (req.query.username) {
      var username = req.query.username
      var user = await models.User.findOne({
        where: { [Op.and]: [{ username: `${username}` }] },
        include: [{
          model: models.Role,
        },
        {
          model: models.Department
        }]
      })
      res.json({ user })
    } else {
      var users = await models.User.findAll({
        include: [{
          model: models.Role,
        },
        {
          model: models.Department
        }]
      })
      res.json({ users })
    }
  } catch (e) {
    console.log(e);
  }
});

router.get('/:id', async function (req, res, next) {
  const id = req.params.id
  var user = await models.User.findOne({
    where: { [Op.and]: [{ id }] },
    include: [{
      model: models.Role,
    },
    {
      model: models.Department
    }]
  })
  res.json({ user })
})

// 获取用户提交的信息并插入数据库
router.post('/', async function (req, res, next) {
  const { departmentId, username, gender, phoneNumber, roleId, roleState } = JSON.parse(req.query.data)
  try {
    var user = await models.User.create({
      departmentId, username, gender, phoneNumber, roleId, roleState, default: false
    })
    res.json({ user: user })
  } catch (e) {
    console.log(e)
  }
})

// 修改用户信息
router.put('/:id', async function (req, res, next) {
  const id = req.params.id
  const { departmentId, username, gender, phoneNumber, roleId, roleState } = JSON.parse(req.query.data)
  try {
    var users = await models.User.update({
      departmentId, username, gender, phoneNumber, roleId, roleState
    }, { where: { id } })

    res.json({ users })
  } catch (e) {
    console.log(e)
  }
})

// 修改用户状态
router.put('/roleState/:id', async function (req, res, next) {
  const id = req.params.id
  const roleState = JSON.parse(req.query.roleState)
  try {
    var users = await models.User.update({
      roleState
    }, { where: { id } })
    res.json({ users })
  } catch (e) {
    console.log(e)
  }
})

// 删除教师信息
router.delete('/:id', async function (req, res, next) {
  const id = req.params.id
  const t = await db.sequelize.transaction();
  try {
    var user = await models.User.findByPk(id)
    await t.commit()
    if (user) {
      user.destroy()
      res.json({ msg: '删除成功' })
    } else {
      res.json({ msg: '不存在该数据' })
    }
  } catch (error) {
    console.log(error);
    await t.rollback()
  }
})

module.exports = router;
